<template>
    <view class="chat">
        <scroll-view
            :style="{ height: `${windowHeight - inputHeight}rpx` }"
            id="scrollview"
            scroll-y="true"
            :scroll-top="scrollTop"
            class="scroll-view"
        >
            <!-- 聊天主体 -->
            <view id="msglistview" class="chat-body">
                <!-- 聊天记录 -->
                <view v-for="(item, index) in msgList" :key="index">
                    <!-- 自己发的消息 -->
                    <view
                        class="item self"
                        v-if="item.fromUser.uid == customerIdBySalesmanId"
                    >
                        <!-- 文字内容 -->
                        <view class="content right">
                            {{ item.message.body.content }}
                        </view>
                        <!-- 头像 -->
                        <view class="avatar">
                            <image
                                v-if="userInfo.avatar"
                                :src="userInfo.avatar"
                                mode="aspectFill"
                                class="pic"
                            ></image>
                            <image
                                v-else
                                :src="defaultAvatar"
                                mode="aspectFill"
                                class="pic"
                            ></image>
                        </view>
                    </view>
                    <!-- 机器人发的消息 -->
                    <view
                        class="item Ai"
                        v-if="item.fromUser.uid !== customerIdBySalesmanId"
                    >
                        <!-- 头像 -->
                        <view class="avatar">
                            <image
                                :src="customerAvatar"
                                mode="aspectFill"
                                class="pic"
                            ></image>
                        </view>
                        <!-- 文字内容 -->
                        <view class="content left">
                            {{ item.message.body.content }}
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>
        <!-- 底部消息发送栏 -->
        <!-- 用来占位，防止聊天消息被发送框遮挡 -->
        <view class="chat-bottom" :style="{ height: `${inputHeight}rpx` }">
            <view class="send-msg" :style="{ bottom: `${keyboardHeight}rpx` }">
                <view class="uni-textarea">
                    <textarea
                        v-model="chatMsg"
                        maxlength="300"
                        confirm-type="send"
                        @confirm="handleSend"
                        :show-confirm-bar="false"
                        :adjust-position="false"
                        @linechange="sendHeight"
                        @focus="focus"
                        @blur="blur"
                        auto-height
                    ></textarea>
                </view>
                <button @click="handleSend" class="send-btn">发送</button>
            </view>
        </view>
    </view>
</template>
<script>
import { baseUrl } from "@/config/tendIdConfig";
import { mapGetters } from "vuex";
export default {
    data() {
        return {
            //键盘高度
            keyboardHeight: 0,
            //底部消息发送高度
            bottomHeight: 0,
            //滚动距离
            scrollTop: 0,
            userId: "",
            //发送的消息
            chatMsg: "",
            msgList: [],
            roomId: "",
            customerAvatar: "",
            customerIdBySalesmanId: "",
            defaultAvatar:
                "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/23/0e6265fd99fa49a9bacf3791420d6de6.png",
        };
    },
    updated() {
        //页面更新时调用聊天消息定位到最底部
        this.scrollToBottom();
    },
    computed: {
        windowHeight() {
            return this.rpxTopx(uni.getSystemInfoSync().windowHeight);
        },
        // 键盘弹起来的高度+发送框高度
        inputHeight() {
            return this.bottomHeight + this.keyboardHeight;
        },
        ...mapGetters(["userInfo"]),
    },
    onLoad(options) {
        this.roomId = options.roomId;
        this.customerAvatar = options?.customerAvatar ?? this.defaultAvatar;
        console.log(options, "options>>>");
        uni.setNavigationBarTitle({
            title: options?.name ?? "对话",
        });
        uni.onKeyboardHeightChange((res) => {
            this.keyboardHeight = this.rpxTopx(res.height - 30);
            if (this.keyboardHeight < 0) this.keyboardHeight = 0;
        });
        this.getHistoryMsg();
    },
    onUnload() {
        uni.offKeyboardHeightChange();
    },
    mounted() {
        this.getCustomerIdBySalesmanId();
        this.readNum();
    },
    methods: {
        getCustomerIdBySalesmanId() {
            //获取当前业务员得客户id
            const token =
                this.$store.getters?.customer_token ||
                uni.getStorageSync("customer_token");
            const that = this;
            uni.request({
                url:
                    baseUrl +
                    `/customer/want_to_be_salesman/getTheCustomerIdBySalesmanId/${that.userInfo.id}`,
                method: "GET",
                header: {
                    Authorization: token,
                },
                success(res) {
                    that.customerIdBySalesmanId = res.data.data;
                },
            });
        },
        // 获取历史消息
        getHistoryMsg() {
            const token =
                this.$store.getters?.customer_token ||
                uni.getStorageSync("customer_token");
            const that = this;
            uni.request({
                url: baseUrl + "/customer/chat_message/public/msg/page",
                method: "GET",
                header: {
                    Authorization: token,
                },
                data: {
                    roomId: that.roomId,
                    pageSize: 50,
                },
                success(res) {
                    const result = res.data.data.list ?? [];
                    that.msgList = result;
                },
            });
        },
        readNum() {
            const token =
                this.$store.getters?.customer_token ||
                uni.getStorageSync("customer_token");
            const that = this;
            uni.request({
                url: baseUrl + "/customer/chat_message/msg/read",
                method: "PUT",
                header: {
                    Authorization: token,
                },
                data: {
                    roomId: that.roomId,
                },
                success(res) {},
            });
        },
        focus() {
            this.scrollToBottom();
        },
        blur() {
            this.scrollToBottom();
        },
        // px转换成rpx
        rpxTopx(px) {
            // 使用 uni.getSystemInfoSync 替换 wx.getSystemInfoSync，支持跨平台
            let deviceWidth = uni.getSystemInfoSync().windowWidth;
            let rpx = (750 / deviceWidth) * Number(px);
            return Math.floor(rpx);
        },
        // 监视聊天发送栏高度
        sendHeight() {
            setTimeout(() => {
                let query = uni.createSelectorQuery();
                query.select(".send-msg").boundingClientRect();
                query.exec((res) => {
                    this.bottomHeight = this.rpxTopx(res[0].height);
                });
            }, 10);
        },
        // 滚动至聊天底部
        scrollToBottom(e) {
            setTimeout(() => {
                let query = uni.createSelectorQuery().in(this);
                query.select("#scrollview").boundingClientRect();
                query.select("#msglistview").boundingClientRect();
                query.exec((res) => {
                    if (res[1].height > res[0].height) {
                        this.scrollTop = this.rpxTopx(
                            res[1].height - res[0].height
                        );
                    }
                });
            }, 15);
        },
        // 发送消息
        handleSend() {
            if (!this.chatMsg) {
                uni.showToast({
                    title: "请输入有效的内容",
                    icon: "none",
                });
                return;
            }
            const token =
                this.$store.getters?.customer_token ||
                uni.getStorageSync("customer_token");
            const that = this;
            uni.request({
                url: baseUrl + "/customer/chat_message/msg",
                method: "POST",
                header: {
                    Authorization: token,
                },
                data: {
                    body: {
                        content: that.chatMsg,
                    },
                    msgType: 1,
                    roomId: that.roomId,
                },
                success(res) {
                    // 将当前发送信息 添加到消息列表。
                    let result = {
                        fromUser: {
                            uid: that.customerIdBySalesmanId,
                        },

                        message: {
                            body: {
                                content: that.chatMsg,
                            },
                        },
                    };
                    that.msgList.push(result);
                    that.chatMsg = "";
                    that.scrollToBottom();
                    that.readNum();
                },
            });
        },
    },
};
</script>
<style lang="scss" scoped>
$chatContentbgc: #1682ff;
$sendBtnbgc: #1682ff;

view,
button,
text,
input,
textarea {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* 聊天消息 */
.chat {
    .scroll-view {
        ::-webkit-scrollbar {
            display: none;
            width: 0 !important;
            height: 0 !important;
            -webkit-appearance: none;
            background: transparent;
            color: transparent;
        }

        // background-color: orange;
        background-color: #f6f6f6;

        .chat-body {
            display: flex;
            flex-direction: column;
            padding-top: 23rpx;
            // background-color:skyblue;

            .self {
                justify-content: flex-end;
            }

            .item {
                display: flex;
                padding: 23rpx 30rpx;
                // background-color: greenyellow;

                .right {
                    background-color: $chatContentbgc;
                    color: #fff;
                }

                .left {
                    background-color: #ffffff;
                }

                // 聊天消息的三角形
                .right::after {
                    position: absolute;
                    display: inline-block;
                    content: "";
                    width: 0;
                    height: 0;
                    left: 100%;
                    top: 10px;
                    border: 12rpx solid transparent;
                    border-left: 12rpx solid $chatContentbgc;
                }

                .left::after {
                    position: absolute;
                    display: inline-block;
                    content: "";
                    width: 0;
                    height: 0;
                    top: 10px;
                    right: 100%;
                    border: 12rpx solid transparent;
                    border-right: 12rpx solid #ffffff;
                }

                .content {
                    position: relative;
                    max-width: 486rpx;
                    border-radius: 8rpx;
                    word-wrap: break-word;
                    padding: 24rpx 24rpx;
                    margin: 0 24rpx;
                    border-radius: 5px;
                    font-size: 32rpx;
                    font-family: PingFang SC;
                    font-weight: 400;
                    // color: #333333;
                    line-height: 42rpx;
                }

                .avatar {
                    display: flex;
                    justify-content: center;
                    width: 78rpx;
                    height: 78rpx;
                    // background: $sendBtnbgc;
                    border-radius: 50%;
                    overflow: hidden;

                    image {
                        width: 78rpx;
                        height: 78rpx;
                        align-self: center;
                    }
                }
            }
        }
    }

    /* 底部聊天发送栏 */
    .chat-bottom {
        width: 100%;
        height: 177rpx;
        background: #f4f5f7;
        transition: all 0.1s ease;

        .send-msg {
            display: flex;
            align-items: flex-end;
            padding: 16rpx 30rpx;
            width: 100%;
            min-height: 177rpx;
            position: fixed;
            bottom: 0;
            background: #fff;
            transition: all 0.1s ease;
        }

        .uni-textarea {
            padding-bottom: 70rpx;

            textarea {
                width: 537rpx;
                min-height: 75rpx;
                max-height: 500rpx;
                background: #f6f6f6;
                border-radius: 8rpx;
                font-size: 32rpx;
                font-family: PingFang SC;
                color: #333333;
                line-height: 43rpx;
                padding: 5rpx 8rpx;
                border-radius: 518rpx 518rpx 518rpx 518rpx;
            }
            .place-holder {
                line-height: 43rpx;
                font-size: 28rpx;
            }
        }

        .send-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 70rpx;
            margin-left: 25rpx;
            width: 118rpx;
            height: 76rpx;
            background: $sendBtnbgc;
            border-radius: 8rpx;
            font-size: 28rpx;
            font-family: PingFang SC;
            font-weight: 400;
            color: #ffffff;
            line-height: 28rpx;
            border-radius: 518rpx 518rpx 518rpx 518rpx;
        }
    }
}
</style>
